#include <stdlib.h>
#include <stdio.h>
#include "myfunc.h"

int main(int argc, char **argv)
{
    Buffer buf;         /* A buffer */
    unsigned char *blk; /* A pointer to a block */
    unsigned char blk_result[64] = {0};
    int i, j, k = 0, count = 0;
    struct Tuple tuple;
    initBuffer(520, 64, &buf);
    for (i = 17; i <= 48; i++)
    {
        if ((blk = readBlockFromDisk(i, &buf)) == NULL)
        {
            printf("Reading Block %d Failed!\n", i);
            return -1;
        }
        else
        {
            printf("-------- Block %.2d --------\n", i);
        }
        // ******************* select ********************
        for (j = 0; j < 7; j++)
        {
            GetTuple(&tuple, j, blk);
            if (tuple.first == 50)
            {
                // save to disk and print
                memcpy((blk_result + k * 8), (blk + j * 8), 8);
                count++;
                k++;
                if (count % 7 == 0)
                {
                    k = 0;
                    writeBlockToDisk(blk_result, 100 + count / 7, &buf);
                    memset(blk_result, 0, 64);
                }
                printf("Find (%d, %d)\n", tuple.first, tuple.second);
            }
        }
        writeBlockToDisk(blk_result, 100 + count / 7, &buf);
        freeBlockInBuffer(blk, &buf);
    }
    printf("Total IO's in this selection:%d", buf.numIO);
    freeBuffer(&buf);
}
